package cn.maihe.elg.operation.centers.guogu.auth;

import cn.maihe.elg.operation.centers.guogu.config.GuoGuCenterInfosConfig;
import cn.maihe.elg.operation.common.auth.Authorization;
import cn.maihe.elg.operation.config.ElgAuthConfig;
import cn.maihe.elg.operation.utils.ElgLogger;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ggy.encrypttools.sm.SMUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.util.Map;

/**
 * @Description 新点签名验签算法
 * 报文签名使用国密消息摘要算法（SM3），将报文字段按照ASCII升序排序，并按照“参数=参数值”的模式，用“&”字符拼接成字符串，最后使用appsecret对报文进行签名。
 * @Author SSX
 * @Date 2025/03/18
 */
@Slf4j
public class GuoGuAuthorization implements Authorization {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final ElgAuthConfig elgAuthConfig;
    private final GuoGuCenterInfosConfig.CenterInfo centerInfo;

    public GuoGuAuthorization(ElgAuthConfig elgAuthConfig, GuoGuCenterInfosConfig.CenterInfo centerInfo) {
        this.elgAuthConfig = elgAuthConfig;
        this.centerInfo = centerInfo;

        Assert.hasText(elgAuthConfig.getPubKey(), () -> "elg系统公钥不能为空");
        Assert.hasText(elgAuthConfig.getPriKey(), () -> "elg系统私钥不能为空");

        Assert.hasText(centerInfo.getAppKey(), () -> centerInfo+"的appKey不能为空");
        Assert.hasText(centerInfo.getAppSecret(), () -> centerInfo+"的appSecret不能为空");

    }

    @Override
    public String signature(Object body, String timestamp) {
        return null;
    }

    @Override
    public boolean verifySignature(Object reqBody, String signedMsg, String timestamp) {
        return false;
    }

    public String signature(String clientId,String body) {
        ElgLogger.debug(log, l -> l.debug("待签名请求对象：{}",body));
        Map<String, GuoGuCenterInfosConfig.ClientInfo> clientInfos = centerInfo.getClientInfos();
        GuoGuCenterInfosConfig.ClientInfo clientInfo = clientInfos.get(clientId);
        String unSigned = String.format("%s&%s&%s", body, clientInfo.getClientId(), clientInfo.getClientSecret());
        ElgLogger.debug(log, l -> l.debug("待签名字符串：{}", unSigned));
        String signed = SMUtils.digestBySM3(unSigned);
        ElgLogger.debug(log, l -> l.debug("签名后字符串：{}", signed));
        return signed;
    }

    public boolean verifySignature(String clientId, String reqBody, String signedMsg) {
        ElgLogger.debug(log, l -> l.debug("待验签请求对象：{}", reqBody));
        boolean verify = this.signature(clientId,reqBody).equalsIgnoreCase(signedMsg);
        ElgLogger.debug(log, l -> l.debug("验签结果：[{}]", verify));
        return verify;
    }

}
